/**
 * Ajax 请求常用方法封装
 */
import * as SSKEYS from './session-storage-keys'
import errorCode from '@/common/errorCode'
import store from '@/store'
import {
	toast,
	showConfirm,
	tansParams
} from '@/common/utils.js'
export class Ajax {
	static ajax({
		method,
		url,
		params,
		headers,
		signal,
		timeout = 10000,
		json = true,
		responseType = null
	}) {
		const urls = getApp().globalData.config.urls
		let baseUrl = urls.pro
		const appPlatform = uni.getStorageSync(SSKEYS.ACCOUNT_APPLICATION_PLATFORM_KEY)
		// console.log(appPlatform)
		if (appPlatform === 'MP-WEIXIN') {
			const info = uni.getAccountInfoSync()
			const envVersion = info.miniProgram.envVersion
			headers['envVersion'] = envVersion
			if (envVersion === 'develop') {
				baseUrl = urls.dev
			} else if (envVersion === 'trial') {
				baseUrl = urls.trial
			} else if(envVersion ==='release'){
				baseUrl = urls.pro
			}
		} else if (appPlatform === 'H5') { //开发环境  生成环境需要切换。
			if (process.env.NODE_ENV === 'development') {
			    baseUrl = urls.h5Dev
			}
			if (process.env.NODE_ENV === 'production') {
			    baseUrl = urls.h5Pro 
			}
			
		}

		if (method === 'GET') {
			let search = null
			if (params) {
				search = Object.keys(params).map(key => encodeURIComponent(key) + '=' + encodeURIComponent(params[
					key])).join('&')
			}
			if (search) {
				url += (url.indexOf('?') === -1 ? '?' : '&') + search
			}

		}
		url = baseUrl + url
		const contentType = json ? 'application/json;charset=UTF-8' :
			'application/x-www-form-urlencoded;charset=UTF-8'

        
		return new Promise((resolve, reject) => {
			uni.request({
					method: method || 'get',
					timeout: timeout || timeout,
					url,
					data: params,
					header: headers,
					dataType: 'json'
				}).then(response => {
					let [error, res] = response
					if (error) {
						toast('后端接口连接异常')
						resolve({
							code: -1,
							msg: '后端接口连接异常'
						})
						return
					}
					const code = res.data.code || 200
					const msg = errorCode[code] || res.data.msg || errorCode['default']
					if (code === 401) {
						showConfirm('登录状态已过期，您可以继续留在该页面，或者重新登录?', {
							showCancel: false
						}).then(res => {
							if (res.confirm) {
								store.dispatch('LogOut').then(res => {
									uni.reLaunch({
										url: '/pages/login'
									})
								})
							}
						})
						resolve({
							code,
							msg: '无效的会话，或者会话已过期，请重新登录。'
						})
					} else if (code === 500) {
						toast(msg)
						resolve({
							code,
							msg
						})
					} else if (code !== 200) {
						toast(msg)
						resolve({
							code,
							msg
						})
					}
					resolve(res.data)
				})
				.catch(error => {
					let {
						message
					} = error
					if (message === 'Network Error') {
						message = '网络连接异常'
					} else if (message.includes('timeout')) {
						message = '系统接口请求超时'
					} else if (message.includes('Request failed with status code')) {
						message = '系统接口' + message.substr(message.length - 3) + '异常'
					}
					toast(message)
					resolve({
						code: -1,
						msg: message
					})
				})
		})
	}

	static get(url, params) {
		return Ajax.ajax({
			method: 'GET',
			url,
			params
		})
	}

	static post(url, params) {
		return Ajax.ajax({
			method: 'post',
			url,
			params
		})
	}

	static put(url, params) {
		return Ajax.ajax({
			method: 'PUT',
			url,
			params
		})
	}

	static delete(url, params) {
		return Ajax.ajax({
			method: 'DELETE',
			url,
			params
		})
	}

	static patch(url, params) {
		return Ajax.ajax({
			method: 'PATCH',
			url,
			params
		})
	}
}
